(function () {
  'use strict';

  angular
    .module('articles')
    .filter('simplify', ArticlesListContentSimplify)
    .controller('ArticlesListController', ArticlesListController);

  ArticlesListController.$inject = ['$scope', 'ArticlesService'];

  function ArticlesListController($scope, ArticlesService) {
    var vm = this;
    vm.showFooter = false;
    vm.isLoading = false;
    vm.articles = ArticlesService.queryByHttp(true);

    vm.showMore = function () {
      if(vm.articles.length == 0) {
        return;
      }

      vm.isLoading = true;
      var last = vm.articles[vm.articles.length - 1];
      var lastItemTime = last.created;
      var moreArts = [];

      ArticlesService.queryMoreByHttp(true, lastItemTime).then(
        // Suc fn
        function (articles) {
          Array.prototype.push.apply(vm.articles, articles);
        },
        // Error fn
        function () {
            // Do nothing
        }
      )
      ['finally'](function (){
        vm.isLoading = false;
      })
    };

    $scope.$on('$getArticleList', function (isGot) {
      if(isGot) {
        vm.showFooter = true;
      }
    });
  }

  ArticlesListContentSimplify.$inject = ['$sce', '$filter'];
  function ArticlesListContentSimplify($sce, $filter) {
    return function (richText) {
      var limit = 70;

      // Remove all of the html tags
      richText= '<p>' + richText + '</p>';
      var htmlText = angular.element(richText).text();
      htmlText = htmlText.trimLeft();
      if (htmlText.length <= limit) {
        return htmlText + '...';
      }

      return $filter('limitTo')(htmlText, limit) + '...';
    }
  }

}());
